import * as React from 'react';

import {IView} from '../types/IView';
import {IAttr} from '../types/IAttr';

import {IViewObject} from './IViewObject';
import AbsViewObject from './AbsViewObject';

export class ImageViewObject extends AbsViewObject<IView> implements IViewObject<IView> {

  viewType = 'image';

  attrs: IAttr[] = [
    {
      name: 'id',
      display: 'ID',
      type: 'string',
      required: true,
      defaultValGenerator: () => {
        return `imageView${this.viewIndex}`;
      }
    },
    {
      name: 'src',
      display: '图片',
      type: 'image',
      required: true,
      defaultValGenerator: () => {
        return '';
      }
    },
    {
      name: 'className',
      display: 'class',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return '';
      }
    },
    {
      name: 'alt',
      display: '描述',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return `图片${this.viewIndex}`;
      }
    }
  ];

  create(designId: string): IView {
    return {
      id: this.generateId(),
      viewType: this.viewType,
      designId,
      style: {
        width: '50px',
        height: '50px'
      },
      attrVals: this.createAttrVals(this.attrs)
    };
  }

  render(view: IView, refUpdater: (view: IView, ref: Element) => void): JSX.Element | null {
    const {attrVals} = view;

    const elemRefUpdater: React.Ref<Element> = el => refUpdater(view, el);
    const props: React.ImgHTMLAttributes<HTMLElement> = {
      id: attrVals.id,
      src: attrVals.src,
      alt: attrVals.alt,
      title: attrVals.alt,
      className: attrVals.className,
      style: attrVals.className ? {} : view.style
    };

    return (
      <img ref={elemRefUpdater} {...props}/>
    );
  }
}

const imageViewObject = new ImageViewObject();
export default imageViewObject;
